package com.woniuxy.thread.commucation;

/**
 * 共享资源,其中的数据只能是0-1
 *
 * @author 老谭 (<a href="http://www.woniuxy.com">蜗牛学苑</a>)
 *
 */
public class Resource {
	private int num;

	/**
	 * 增加数据
	 */
	public synchronized void add() {
		while (num != 0) {
			try {
				wait(); // 等待被唤醒,锁会被释放
				System.out.println("wait");
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		num++;
		System.out.println(num);

		notify();// 唤醒，通知其他访问该方法的线程来执行
	}

	public synchronized void sub() {
		while (num != 1) {
			try {
				wait();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		num--;
		System.out.println(num);
		notify();
	}

	public int getNum() {
		return this.num;
	}

}
